#include <event2/event.h>
#include <event2/listener.h>
#include <iostream>
#include <signal.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
using namespace std;

static const char *ip = "192.168.232.128";
static const int port = 12345;

void listener_cb(struct evconnlistener *listener, evutil_socket_t sockfd, struct sockaddr *addr, int socklen, void *args) {
    cout << "listener callback function" << endl;
}

int main() {
    // 忽略管道信号，避免发送数据给已关闭socket
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
        cout << "set pipe signal error" << endl;
        return 1;
    }
    // 创建 libevent 上下文
    event_base *base = event_base_new();
    if (base) {
        cout << "create new event base" << endl;
    }

    sockaddr_in address;
    bzero(&address, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_port = htons(port);
    inet_pton(AF_INET, ip, &address.sin_addr);
    
    // 监听端口设置 socket - bind - listen
    evconnlistener *listener = evconnlistener_new_bind(base,   // 上下文
        listener_cb,                // 监听回调函数
        base,                       // 回调函数参数
        LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE,  // 地址重用 | 释放时关闭socket
        5,  // 相当于 listen(5) 参数
        (struct sockaddr*)&address,
        sizeof(address)     // 创建 socket
        );

    // 事件分发处理
    event_base_dispatch(base);


    // 释放资源
    assert(listener);
    evconnlistener_free(listener);
    assert(base);
    event_base_free(base);

}